#!/usr/bin/env bash
# 构建哪些文档

# ubuntu:22.04
# apt-get update
# apt install language-pack-zh-hans language-pack-zh-hans-base language-pack-gnome-zh-hans language-pack-gnome-zh-hans-base
# apt-get install -y python3 wget make pandoc texlive-full
# apt-get install -y xz-utils texlive-xetex texlive-lang-chinese xzdec
# apt-get install ttf-wqy-microhei ttf-wqy-zenhei
# tlmgr init-usertree
# tlmgr option repository ftp://tug.org/historic/systems/texlive/2017/tlnet-final
# tlmgr install adjustbox babel-german background bidi collectbox csquotes everypage filehook footmisc footnotebackref framed fvextra letltxmacro ly1 mdframed mweights needspace pagecolor sourcecodepro sourcesanspro titling ucharcat ulem unicode-math upquote xecjk xurl zref


CURDIR=`pwd`
# MAINFONT="WenQuanYi Micro Hei"
MAINFONT='PingFang SC'
MONOFONT="WenQuanYi Micro Hei Mono"
_version_tag=$(date '+%Y-%m-%d')
templateV2File=templates/eisvogel.tex
DocxTemplateDocxFile=templates/rmd-minion-reference.docx
MergeTocToolScript=scripts/merge_by_toc.py
DockRootDir="product"
dist="dist/pdf"
build_docx=no
# 构建全部文档
build_all=yes
# 构建 latex 文档
build_tex=no
# 只 构建 mtk 文档
only_build_mtk=no
# 只 构建 mdb 文档
only_build_mdb=no
# 只 构建 sca 文档
only_build_sca=no
# 只 构建 mvd 文档
only_build_mvd=no
# 只 构建 mogdb 文档
only_build_mogdb=no
# 只 构建 mogha～ 文档
only_build_mogha=no
# 只 构建 manage～ 文档
only_build_manager=no
# 只 构建 stack 文档
only_build_stack=no
# 只 构建 uqbar 文档
only_build_uqbar=no

function h1() {
    printf "\n${underline}${bold}${blue}[build] %s${reset}\n" "$@"
}

function h2() {
    printf "\n${underline}${bold}${white}[build] %s${reset}\n" "$@"
}

function h3() {
    printf "\n\t${underline}${bold}${white}[build] %s${reset}\n" "$@"
}

function info() {
     printf "${white}➜ [build] %s${reset}\n" "$@"
}

function success() {
    printf "${green}✔ [build] %s${reset}\n" "$@"
}

function error() {
    printf "${red}✖ [build] %s${reset}\n" "$@"
}

function warn() {
    printf "${tan}➜ [build] %s${reset}\n" "$@"
}

function bold() {
    printf "${bold}[build] %s${reset}\n" "$@"
}

function note() {
    printf "\n${underline}${bold}${blue}Note:${reset} ${blue}[build] %s${reset}\n" "$@"
}

# 生成PDF
function _generate_pdf() {
    language=${1}
    DocFile=${2}
    DocTitle=${3}
    DocOutPutFile=${4}
    # +RTS -M4096M -RTS
    osPlat=`uname`
    pdfEngine="pdf-engine"
    smart=""
    input="markdown+smart+markdown_in_html_blocks+grid_tables+multiline_tables+escaped_line_breaks"
    copyrightFile=""
    CJKmainfont=""
    docTocName=""
    if [[ ${language} == "zh" ]]; then
        copyrightFile="templates/copyright_zh.tex"
        docTocName="目录"
        CJKmainfont="${MAINFONT}"
    fi
    if [[ ${language} == "en" ]]; then
        copyrightFile="templates/copyright_en.tex"
        docTocName="Contents"
        CJKmainfont=""
    fi
    template="--template=${templateV2File}"
    if [[ "${build_docx}" == "yes" ]]; then
        template="--reference-doc=${DocxTemplateDocxFile}"
    fi
    DocTitle=${DocTitle//-/ }
    pandoc -N --toc --${pdfEngine}=xelatex ${smart} \
        -f ${input} \
        ${template} \
        --toc-depth=4 \
        -V title="${DocTitle}" \
        -V author="Enmotech Inc." \
        -V date="${_version_tag}" \
        -V mainfont="${MAINFONT}" \
        -V sansfont="${MAINFONT}" \
        -V monofont="${MONOFONT}" -V CJKmainfont="${CJKmainfont}" \
        -V include-after="\\input{${copyrightFile}}" \
        --listings \
        --extract-media=/tmp/pandoc/ \
        --variable geometry:top=2.0cm \
        --variable geometry:bottom=2.0cm \
        --variable geometry:left=1.5cm \
        --variable geometry:right=1.5cm \
        --variable title-meta="${DocTitle}" \
        --variable author-meta="Enmotech Inc." \
        --variable creator-meta="Enmotech Inc." \
        --variable listings-disable-line-numbers="true" \
        --variable page-background="media/mogdb-logo.png" \
        --variable toc-own-page="true" \
        --variable toc-title="${docTocName}" \
        --variable titlepage="true" \
        --variable table-use-row-colors="true" \
        --variable colorlinks="true" \
        --variable toccolor="Blue" \
        --variable caption-justification=centering \
        --columns 40 \
        "${DocFile}" -s -o "${DocOutPutFile}"

    retCode=$?

    if [[ ${retCode} == 0 ]]; then
        success "[${DocOutPutFile}] successfully"
    else
        error   "[${DocOutPutFile}] failed"
    fi
}

# mogdb 多语言定义
mogdbDocsLanguages=("zh" "en")

# mogdb 版本定义
mogdbDocsVersions=("v3.0" "v3.1")

# 不能使用下划线
declare -A mogdbZn210Title=( \
    ["toc_parameters-and-tools"]="MogDB-数据库参数和工具指南" \
    ["toc_datatypes-and-sql"]="MogDB-数据库SQL语法指南" \
    ["toc_glossary"]="MogDB-数据库术语表" \
    ["toc_faqs"]="MogDB-数据库常见问题解答" \
    ["toc_error"]="MogDB-数据库错误信息" \
    ["toc_performance"]="MogDB-数据库性能优化指南" \
    ["toc_about"]="MogDB-数据库概述" \
    ["toc_secure"]="MogDB-数据库安全指南" \
    ["toc_quickstart"]="MogDB-数据库快速入门" \
    ["toc_manage"]="MogDB-数据库管理指南" \
    ["toc_install"]="MogDB-数据库安装指南" \
    ["toc_system-catalogs-and-functions"]="MogDB-数据库系统表及函数指南" \
    ["toc_dev"]="MogDB-数据库开发者指南" \
    ["toc_extension-referecne"]="MogDB-数据库插件指南" \
)
declare -A mogdbEn210Title=( \
    ["toc_parameters-and-tools"]="MogDB-Database-Parameter-and-Tool-Reference" \
    ["toc_datatypes-and-sql"]="MogDB-Database-SQL-Language-Reference" \
    ["toc_glossary"]="MogDB Database-Glossary" \
    ["toc_faqs"]="MogDB-Database-FAQs" \
    ["toc_error"]="MogDB-Database-Error-Messages" \
    ["toc_performance"]="MogDB-Database-Performance-Tuning" \
    ["toc_about"]="MogDB-Database-Overview" \
    ["toc_secure"]="MogDB-Database-Security-Guide" \
    ["toc_quickstart"]="MogDB-Database-Quick-Start" \
    ["toc_manage"]="MogDB-Database-Administrator-Guide" \
    ["toc_install"]="MogDB-Database-Installation-Guide" \
    ["toc_system-catalogs-and-functions"]="MogDB-Database-System-View-and-Function-Reference" \
    ["toc_dev"]="MogDB-Database-Developer-Guide" \
    ["toc_extension-referecne"]="MogDB-Database-Extension-Reference" \
)

function generate_mogdb_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#mogdbDocsVersions[@]};j++))
        do
            version=${mogdbDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-mogdb" $language $version mogdbZn210Title
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-mogdb" $language $version mogdbEn210Title
            fi
        done
    done
}

mtkDocsVersions=("v2.0")

declare -A mtkZnTitle=( \
    ["toc"]="MogDB-MTK-指南" \
)

declare -A mtkEnTitle=( \
    ["toc"]="MogDB-MTK-Reference" \
)

function generate_mtk_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#mtkDocsVersions[@]};j++))
        do
            version=${mtkDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-mtk" $language $version mtkZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-mtk" $language $version mtkEnTitle
            fi
        done
    done
}

managerDocsVersions=("v1.0")

declare -A managerZnTitle=( \
    ["toc"]="MogDB-Manager-指南" \
)

declare -A managerEnTitle=( \
    ["toc"]="MogDB-Manager-Reference" \
)

function generate_manager_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#managerDocsVersions[@]};j++))
        do
            version=${managerDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-manager" $language $version managerZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-manager" $language $version managerEnTitle
            fi
        done
    done
}

# scaDocsVersions=("v4.0" "v4.1" "v5.0" "v5.1")
scaDocsVersions=("v5.0" "v5.1")

declare -A scaZnTitle=( \
    ["toc"]="MogDB-SCA-指南" \
)

declare -A scaEnTitle=( \
    ["toc"]="MogDB-SCA-Reference" \
)

function generate_sca_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#scaDocsVersions[@]};j++))
        do
            version=${scaDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-sca" $language $version scaZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-sca" $language $version scaEnTitle
            fi
        done
    done
}

mvdDocsVersions=("v2.0" "v2.4")

declare -A mvdZnTitle=( \
    ["toc"]="MogDB-MVD-指南" \
)

declare -A mvdEnTitle=( \
    ["toc"]="MogDB-MVD-Reference" \
)

function generate_mvd_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#mvdDocsVersions[@]};j++))
        do
            version=${mvdDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-mvd" $language $version mvdZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-mvd" $language $version mvdEnTitle
            fi
        done
    done
}

mogHADocsVersions=("v2.0" "v2.3")

declare -A mogHAZnTitle=( \
    ["toc"]="MogDB-MogHA-指南" \
)

declare -A mogHAEnTitle=( \
    ["toc"]="MogDB-MogHA-Reference" \
)

function generate_mogha_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#mogHADocsVersions[@]};j++))
        do
            version=${mogHADocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-mogha" $language $version mogHAZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-mogha" $language $version mogHAEnTitle
            fi
        done
    done
}

ptkDocsVersions=("v0.5")

declare -A ptkZnTitle=( \
    ["toc"]="MogDB-PTK-指南" \
)

declare -A ptkEnTitle=( \
    ["toc"]="MogDB-PTK-Reference" \
)

function generate_ptk_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#ptkDocsVersions[@]};j++))
        do
            version=${ptkDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-ptk" $language $version ptkZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-ptk" $language $version ptkEnTitle
            fi
        done
    done
}

mdbDocsVersions=("v1.0")

declare -A mdbZnTitle=( \
    ["toc"]="MogDB-MDB-指南" \
)

declare -A mdbEnTitle=( \
    ["toc"]="MogDB-MDB-Reference" \
)

function generate_mdb_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#mdbDocsVersions[@]};j++))
        do
            version=${mdbDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-mdb" $language $version mdbZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-mdb" $language $version mdbEnTitle
            fi
        done
    done
}

stackDocsVersions=("v1.0.0")

declare -A stackZnTitle=( \
    ["toc"]="MogDB-Stack-指南" \
)

declare -A stackEnTitle=( \
    ["toc"]="MogDB-Stack-Reference" \
)

function generate_stack_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#stackDocsVersions[@]};j++))
        do
            version=${stackDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-mogdb-stack" $language $version stackZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-mogdb-stack" $language $version stackEnTitle
            fi
        done
    done
}

uqbarDocsVersions=("v1.1")

declare -A uqbarZnTitle=( \
    ["toc"]="Uqbar-指南" \
)

declare -A uqbarEnTitle=( \
    ["toc"]="Uqbar-Reference" \
)

function generate_uqbar_pdf() {
    for(( i=0;i<${#mogdbDocsLanguages[@]};i++))
    do
        language=${mogdbDocsLanguages[i]}
        for(( j=0;j<${#uqbarDocsVersions[@]};j++))
        do
            version=${uqbarDocsVersions[j]}
            if [[ "$language" == "zh" ]]; then
                _generate_docs_pdf "docs-uqbar" $language $version uqbarZnTitle
            elif [[ "$language" == "en" ]]; then
                _generate_docs_pdf "docs-uqbar" $language $version uqbarEnTitle
            fi
        done
    done
}

function _generate_docs_pdf() {
    local docsName=$1
    local language=$2
    local version=$3
    local title=$(declare -p "$4")
    eval "declare -A local ref"=${title#*=}
    for key in ${!ref[@]};do
        dir=${DockRootDir}/${language}/${docsName}/${version}
        tocFileName=${key}.md
        outFileTitle=${ref[$key]}
        outFileDir=${dist}/${language}/${docsName}/${version}   # dist/en/docs-mogdb/v2.1.0
        outFileFullDir=${CURDIR}/${outFileDir}                  # `pwd`/dist/en/docs-mogdb/v2.1.0/
        outFileBaseName="${outFileTitle}"                       # MogDB-数据库参数和工具指南
        outFileName="${outFileDir}"/"${outFileBaseName}"        # dist/en/docs-mogdb/v2.1.0/MogDB-数据库参数和工具指南
        outFileFullName=${CURDIR}/${outFileName}                # `pwd`/dist/en/docs-mogdb/v2.1.0/MogDB-数据库参数和工具指南
        mkdir -p "${outFileDir}"
        cd $dir
        info "${language}/${version}/${outFileBaseName} to \"${outFileName}.md\" "
        info "$MergeTocToolScript "${tocFileName}" \"${outFileName}.md\""
        $CURDIR/$MergeTocToolScript "${tocFileName}" "${outFileFullName}.md"
        cd $CURDIR
        info "${language}/${version}/$outFileBaseName.pdf"
        if [[ "${build_tex}" == "yes" ]]; then
            _generate_pdf "${language}" "${outFileFullName}.md" "$outFileTitle" "${outFileFullName}.tex"
        fi
        if [[ "${build_docx}" == "yes" ]]; then
            _generate_pdf "${language}" "${outFileFullName}.md" "$outFileTitle" "${outFileFullName}.docx"
        fi
        _generate_pdf "${language}" "${outFileFullName}.md" "$outFileTitle" "${outFileFullName}.pdf"
    done
}

function _usage()
{
  ###### U S A G E : Help and ERROR ######
  cat <<EOF
  $0 $Options
  $*
          Usage: $0 <[options]>
          Options:
                  --all             build all docs pdf
                  --mogdb           build mogdb docs pdf
                  --sca             build sca docs pdf
                  --mvd             build mvd docs pdf
                  --mtk             build mtk docs pdf
                  --mdb             build mdb docs pdf
                  --mogha           build mogha docs pdf
                  --manager         build manager docs pdf
                  --stack           build stack docs pdf
                  --nobuild         not build pdf
                  --tex             build tex file
                  --docs            build docs file
                  --uqbar           build uqbar file
                  -u | --upload     upload build pdf to oss
EOF
  exit 0
}

###### some declarations for this example ######
Options=$@
Optnum=$#
##################################################################
#######  "getopts" with: short options  AND  long options  #######
#######            AND  short/long arguments               #######

# NOTE: This requires GNU getopt.  On Mac OS X and FreeBSD, you have to install this
# separately; see below.
TEMP=$(getopt -o h,u --long help,mtk,mdb,sca,mvd,nobuild,mogha,mogdb,stack,manager,ptk,upload,tex,docs,uqbar\
              -n 'buld_pdf' -- "$@")

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around '$TEMP': they are essential!
eval set -- "$TEMP"

while true; do
  case "$1" in
    -h | --help  ) _usage; shift ;;
    --nobuild    ) build_all=no; shift       ;;
    -u | --upload) upload=yes; shift       ;;
    --mtk        ) build_all=no;only_build_mtk=yes; shift       ;;
    --sca        ) build_all=no;only_build_sca=yes; shift       ;;
    --mvd        ) build_all=no;only_build_mvd=yes; shift       ;;
    --mdb        ) build_all=no;only_build_mdb=yes; shift       ;;
    --mogha      ) build_all=no;only_build_mogha=yes;shift      ;;
    --mogdb      ) build_all=no;only_build_mogdb=yes;shift      ;;
    --manager    ) build_all=no;only_build_manager=yes;shift      ;;
    --ptk        ) build_all=no;only_build_ptk=yes;shift        ;;
    --stack      ) build_all=no;only_build_stack=yes;shift        ;;
    --uqbar      ) build_all=no;only_build_uqbar=yes;shift        ;;
    --tex        ) build_tex=yes;shift      ;;
    --docs       ) build_docx=yes;shift      ;;
    * ) break ;;
  esac
done

if [[ ${nobuild} != "no" ]]; then
    # build mtk pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_mtk}" == "yes" ]]; then
        h1 "Build MTK "
        generate_mtk_pdf
    fi

    # build sca pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_sca}" == "yes" ]]; then
        h1 "Build Sca "
        generate_sca_pdf
    fi

    # build mvd pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_mvd}" == "yes" ]]; then
        h1 "Build MVD "
        generate_mvd_pdf
    fi

    # build mogha pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_mogha}" == "yes" ]]; then
        h1 "Build MogHA "
        generate_mogha_pdf
    fi

    # build mogdb pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_mogdb}" == "yes" ]]; then
        h1 "Build MogDB "
        generate_mogdb_pdf
    fi
        # build mogdb pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_manager}" == "yes" ]]; then
        h1 "Build MogDB Manager"
        generate_manager_pdf
    fi
    # build ptk pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_ptk}" == "yes" ]]; then
        h1 "Build PTK "
        generate_ptk_pdf
    fi
    # build mdb pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_mdb}" == "yes" ]]; then
        h1 "Build MDB "
        generate_mdb_pdf
    fi
    # build ptk pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_stack}" == "yes" ]]; then
        h1 "Build Stack "
        generate_stack_pdf
    fi
        # build Uqbar pdf
    if [[ "${build_all}" == "yes" ]] || [[ "${only_build_uqbar}" == "yes" ]]; then
        h1 "Build Uqbar "
        generate_uqbar_pdf
    fi
fi



function upload_oss() {

    if [ $# != 4 ]
    then
      echo "missing param for upload_oss"
      exit 1
    fi
    host="oss-cn-beijing.aliyuncs.com"
    bucket="mogdb"
    ak=$1
    sk=$2
    osshost=$bucket.$host
    src=$3
    dst=$4
    resource="/${bucket}/${dst}"
    content_type=$(file -ib "${src}" | awk -F ";" '{print $1}')
    date_value="$(TZ=GMT env LANG=en_US.UTF-8 date +'%a, %d %b %Y %H:%M:%S GMT')"
    string_to_sign="PUT\n\n${content_type}\n${date_value}\n${resource}"
    signature=$(echo -en "$string_to_sign" | openssl sha1 -hmac "${sk}" -binary | base64)
    url=http://${osshost}/${dst}
    echo "upload ${src} to ${url}"
    # shellcheck disable=SC2006
    status_code=`curl -isSL -X PUT \
        -o resp.txt \
        -w "%{http_code}" \
        -T "${src}" \
        -H "Host: ${osshost}" \
        -H "Date: ${date_value}" \
        -H "Content-Type: ${content_type}" \
        -H "Authorization: OSS ${ak}:${signature}" \
        "${url}"`
    cat resp.txt
    if [ "${status_code}" != 200 ]
    then
      echo "upload failed"
      exit 1
    fi
    rm -rf resp.txt
}

if [[ "${upload}" == "yes" ]]; then
    OLDIFS="$IFS"
    IFS=$'\n'
    for file in `find ./dist/pdf -name '*.pdf'`
    do
        h1 "upload file ${file}"
        distFle=${file:11}
        distFle="docs-pdf/"${distFle}
        upload_oss ${OSS_AK} ${OSS_SK} ${file} ${distFle}
    done
    IFS="$OLDIFS"
fi
